package chen.web.test.blog;

import java.lang.reflect.InvocationTargetException;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.Assert;

import chen.web.blog.Blog;
import chen.web.blog.BlogManager;
import chen.web.test.TestUtils;
import chen.web.user.Account;
import chen.web.user.EmailAlreadyBeenRegisteredException;
import chen.web.user.NicknameAlreadyBeenRegisteredException;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"/test.xml"})
public class BlogManagerTesting {

	private TestUtils tu = null;
	private @Autowired ApplicationContext context;
	private @Autowired BlogManager bm;
	
	Account testAcc = null;
	@Before 
	public void setUp() throws NicknameAlreadyBeenRegisteredException, EmailAlreadyBeenRegisteredException, SecurityException, IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, NoSuchFieldException, InstantiationException {
		tu = new TestUtils(context);
		testAcc = tu.setupAccount();
		tu.setCurrentAccount(testAcc);
	}
	
	@Test
	public void testBlogCRUD(){
		//create
		Blog blog = new Blog(testAcc);
		blog.setDescription("fdsafdsafdasfdsaf");
		blog.setName("fdsafadsfdasf");
		blog = bm.create(blog);
		Assert.isTrue(blog != null);
		Assert.isTrue(blog.getId() != 0);
		//get by account
		blog = bm.getBlog(testAcc);
		Assert.isTrue(blog != null);
		//get by id
		blog = bm.getBlog(blog.getId());
		Assert.isTrue(blog != null);
		//update
		blog.setDescription("aaaa");
		blog.setName("aaaa");
		bm.update(blog);
		blog = bm.getBlog(blog.getId());
		Assert.isTrue(blog.getName().equals("aaaa"));
		Assert.isTrue(blog.getDescription().equals("aaaa"));
		//remove
		bm.deleteBlog(blog);
		blog = bm.getBlog(blog.getId());
		Assert.isNull(blog);
	}
	
	@After
	public void teardown(){
		tu.teardownAccount(testAcc);
	}
}
